package com.xm.apd.nettyserver.netty;

import android.util.Log;

import java.nio.ByteOrder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * Created by XMclassmate on 2017/12/18.
 */

public class MessgeDecoder extends LengthFieldBasedFrameDecoder {

    private String tag = "[MessageDecoder]";
    private static final int MAX_BUF = 5*1024;
    public MessgeDecoder() {
        super(ByteOrder.LITTLE_ENDIAN,MAX_BUF,12,4,0,0,true);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx,in);
        if (frame == null)
            return null;
        if (Message.verifyHead(frame)){
            try {
                Message message = new Message(frame);
                return message;
            }catch (Exception e){
                e.printStackTrace();
                Log.e(tag,"解码出错");
                ctx.close();
                return null;
            }
        }
        return frame.resetReaderIndex();
    }
}
